package com.jsgt.greekfire.ui.mine.user.changetradingpwd

import android.os.CountDownTimer
import android.text.Selection
import android.text.Spannable
import android.text.TextUtils
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.widget.CompoundButton
import android.widget.EditText
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.fhx.core.base.BaseActivity
import com.fhx.core.utils.ToastUtils
import com.jsgt.greekfire.R
import com.jsgt.greekfire.bean.UserBean
import com.jsgt.greekfire.event.TransferEvent
import com.jsgt.greekfire.factory.UserViewModelFactory
import com.jsgt.greekfire.viewmodel.UserViewModel
import kotlinx.android.synthetic.main.activity_change_trading_pwd.*
import org.greenrobot.eventbus.EventBus

/**
 * 修改交易密码
 * author fhx
 * create time 2020/4/23 15:22
 **/
class ChangeTradingPwdActivity : BaseActivity() {
    private val userViewModel: UserViewModel by lazy {
        ViewModelProvider(
            this,
            UserViewModelFactory()
        ).get(UserViewModel::class.java)
    }
    private var countDown: CountDownTimer? = null
    override fun getLayoutId(): Int = R.layout.activity_change_trading_pwd

    override fun main() {
        title = getString(R.string.change_trading_pwd)
        txvPhone.text = UserBean.instance.mobile
        trading_pwd_cb.setOnCheckedChangeListener(object : CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
                if (isChecked) {
                    trading_pwd_et.transformationMethod =
                        HideReturnsTransformationMethod.getInstance()
                } else {
                    trading_pwd_et.transformationMethod =
                        PasswordTransformationMethod.getInstance()
                }
                endSelection(trading_pwd_et)
            }
        })

        re_trading_pwd_cb.setOnCheckedChangeListener(object :
            CompoundButton.OnCheckedChangeListener {
            override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
                if (isChecked) {
                    re_trading_pwd_et.transformationMethod =
                        HideReturnsTransformationMethod.getInstance()
                } else {
                    re_trading_pwd_et.transformationMethod =
                        PasswordTransformationMethod.getInstance()
                }
                endSelection(re_trading_pwd_et)
            }
        })

        send_code_tv.setOnClickListener {
            userViewModel.sendSMS(UserBean.instance.mobile!!)
        }
        complete_tv.setOnClickListener {
            submit()
        }
        userViewModel.updateTradingPwdLiveData.observe(this, Observer {
            showProgress(false)
            ToastUtils.show(this, getString(R.string.complete))
            EventBus.getDefault().post(TransferEvent(""))
            finish()
        })
        userViewModel.sendSmsLiveData.observe(this, Observer {
            send_code_tv.isEnabled = false
            countDown = object : CountDownTimer(60000, 1000) {
                override fun onFinish() {
                    send_code_tv.isEnabled = true
                    send_code_tv.text = getString(R.string.send_sms_code)
                }

                override fun onTick(millisUntilFinished: Long) {
                    //加500是因为有时候不是特别准确，比如从6000直接跳到了4912
                    send_code_tv.text =
                        "${(millisUntilFinished + 500) / 1000}${getString(R.string.second)}"
                }
            }
            countDown?.start()
        })
        userViewModel.checkSMSLiveData.observe(this, Observer {
            val tradingPwd = trading_pwd_et.text.toString().trim()
            userViewModel.updateTradingPwd(tradingPwd)
        })
        userViewModel.errorLiveData.observe(this, Observer {
            showProgress(false)
        })
    }

    private fun submit() {
        val tradingPwd = trading_pwd_et.text.toString().trim()
        val reTradingPwd = re_trading_pwd_et.text.toString().trim()
        if (tradingPwd.length < 6) {
            ToastUtils.show(this, getString(R.string.wallet_trading_pwd_warning))
            return
        }
        if (!TextUtils.equals(tradingPwd, reTradingPwd)) {
            ToastUtils.show(this, getString(R.string.wallet_pwd_warning))
            return
        }
        val code = verify_code_et.text.toString().trim()
        if (TextUtils.isEmpty(code)) {
            ToastUtils.show(this, getString(R.string.bind_phone_input_verification_code))
            return
        }
        showProgress(true)
        userViewModel.checkSMSCode(UserBean.instance.mobile!!, code)
    }

    override fun onDestroy() {
        super.onDestroy()
        countDown?.cancel()
        countDown = null
    }

    /**
     * 设置EditText游标至末尾
     */
    fun endSelection(editText: EditText) {
        val text: Spannable? = editText.text
        if (text != null) {
            Selection.setSelection(text, text.length)
        }
    }
}